import {uSelectDevShowData} from '@/api/liveDataShow'
import {selectSimpleDevList} from '@/api/public'
import {getUserId} from '@/libs/auth'

function useDeviceHook() {
  const simpleDevList = ref<SimpleDeviceData[]>([])
  const setSimpleDevList = (data: SimpleDeviceData[]) => {
    simpleDevList.value = data
  }
  const getSimpleDevList = computed(() => simpleDevList.value)

  function updateSimpleDevList({
    updateList,
    success
  }: {
    updateList: boolean
    success?: (data: SimpleDeviceData[]) => void
  }) {
    const userId = getUserId()
    if (!userId) return
    selectSimpleDevList({userId})
      .then(res => {
        if (updateList) {
          setSimpleDevList(res.data)
        }
        success && success(res.data)
      })
      .catch(err => {})
  }

  const liveData = ref<LiveData.DevLiveData | undefined>(undefined)
  const getLiveData = computed(() => liveData.value)
  function setLiveData(data: LiveData.DevLiveData | undefined) {
    liveData.value = data
  }
  function updateLiveData({
    devId,
    success,
    updateDataSource
  }: {
    devId: number
    updateDataSource?: boolean
    success?: (data: LiveData.DevLiveData) => void
  }) {
    uSelectDevShowData({devId})
      .then(res => {
        updateDataSource && setLiveData(res.data)
        success && success(res.data)
      })
      .catch(err => {
        setLiveData(undefined)
      })
  }

  return {
    simpleDevList: getSimpleDevList,
    updateSimpleDevList,
    updateLiveData,
    liveData: getLiveData
  }
}

export default useDeviceHook
